import {message} from 'antd'
import WeaWfFinancial from '../wea-wf-financial/index'
import cloneDeep from 'lodash/cloneDeep'
import trim from 'lodash/trim'
import classNames from 'classnames'
import './style/index.css'
import * as InputUtil from './util/index'

class Main extends React.Component {
	constructor(props) {
		super(props);
		const formatvalue = this.transFormatValue(props.value, props.format);
		this.state = {
			value: props.value ? props.value : '',
			formatvalue:formatvalue,
			isonfocus:false,
			location: -1
		};
	}
	componentWillReceiveProps(nextProps) {
		if(this.state.value !== nextProps.value || this.props.format !== nextProps.format || nextProps.defaultFocus) {
			const formatShowValue = this.transFormatValue(nextProps.value, nextProps.format);
			let _state = {
				value: nextProps.value,
				formatvalue:formatShowValue
			};
			if(nextProps.defaultFocus !== this.props.defaultFocus && nextProps.defaultFocus){
				_state.isonfocus = true;
			}
			this.setState(_state);
		}
	}
	shouldComponentUpdate(nextProps, nextState) {
		if(this.props.defaultFocus && this.props.defaultFocus !== nextProps.defaultFocus)	//延时失去焦点时不渲染组件
			return false;
		return nextProps.value !== this.props.value ||
			nextProps.viewAttr !== this.props.viewAttr ||
			nextState.value !== this.state.value ||
			nextState.isonfocus !== this.state.isonfocus ||
			nextState.formatvalue !== this.state.formatvalue ||
			nextProps.format !== this.props.format ||
			nextProps.showhtml !== this.props.showhtml ||
			nextProps.emptyShowContent !== this.props.emptyShowContent ||
			nextProps.fieldName !== this.props.fieldName;
	}
	componentDidUpdate(prevProps, prevState){
		if(this.state.isonfocus === true && prevState.isonfocus === false)
			this.setLocation();
	}
	render() {
		let {isonfocus,formatvalue} = this.state;
		let {viewAttr,style,fieldid,fieldName,detailtype,qfws,format,isDetail,emptyShowContent,showhtml} = this.props;
		let value = this.state.value;
		if(detailtype !==1){
			value = trim(value).length > 0 ? value.replace(/\,/g,'') : '';
		}
		const numberType = parseInt(format.numberType)||0;
		if(!isonfocus && numberType === 100){	//财务表览
			return <WeaWfFinancial type={2} finNum={format.finaNum} className={`finarea_${fieldid}`} viewAttr={viewAttr}
				value={value} clickEvent={this.doFocusEvent.bind(this,true)} />
		}
		if(numberType === 2 && (format.formatPattern == "1" || format.formatPattern == "4")){
			//格式化值负数则变为红色
			style["color"] = !isonfocus && InputUtil.judgeIsNumber(value) && parseFloat(value) < 0 ? "#FF0000" : "inherit";
		}
		const chinglish = detailtype === 4 ? InputUtil.convertAmountChinese(value) : "";
		let domArr = new Array();
		if(viewAttr === 1){
			if(detailtype === 4){
				if(!isDetail){
					domArr.push(<span style={style}>{formatvalue}</span>);
					domArr.push(<br />);
				}
				domArr.push(<span id={`${fieldName}span`} style={style}>{chinglish}</span>);
			}else{
				if(!!showhtml)
					formatvalue = showhtml;
				domArr.push(<span id={`${fieldName}span`} style={style} dangerouslySetInnerHTML={{__html:formatvalue}}></span>);
			}
			return(
				<span>
					{domArr}
					<input type="hidden" id={fieldName} name={fieldName} value={value}/>
				</span>
			)
		}else{
			let className = `wf-input wf-input-${detailtype} ${isDetail ? "wf-input-detail" : "wf-input-main"} wf-input-field${fieldid}`;
			let onKeyPressEvent = "";
			if(detailtype === 2)
				onKeyPressEvent = this.doKeyPressCheckInteger.bind(this);
			else if(detailtype === 3 || detailtype === 4 || detailtype === 5)
				onKeyPressEvent = this.doKeyPressCheckFloat.bind(this);
			if(detailtype === 4){	//金额转换字段
				domArr.push(<input ref="inputEle" type="text" className={className}
							id={fieldName} name={fieldName}
							value={isonfocus?value:(isDetail?chinglish:formatvalue)}
							onChange={this.setInputText.bind(this)}
							onKeyDown={this.doKeyDown.bind(this)}
							onKeyPress={onKeyPressEvent}
							onFocus={this.doFocusEvent.bind(this,true)}
							onBlur={this.doFocusEvent.bind(this,false)}
							style={style} />);
				if(!isDetail){
					domArr.push(<br />);
					domArr.push(<input type="text" disabled={true} value={chinglish} className={`${className} wf-input-chinese`} style={style} />);
				}
			}else {
				//支持可编辑无值时显示灰色默认值
				emptyShowContent = emptyShowContent || "";
				if(!isonfocus && emptyShowContent !== "" && formatvalue.toString() === ""){
					style["color"] = "#A5A5A5";
					formatvalue = emptyShowContent;
				}else{
					if(!"color" in style)
						style["color"] = "inherit";
				}
				domArr.push(<input ref="inputEle" type="text" className={className}
							id={fieldName} name={fieldName}
							value={isonfocus?value:formatvalue}
							onChange={this.setInputText.bind(this)}
							onKeyDown={this.doKeyDown.bind(this)}
							onKeyPress={onKeyPressEvent}
							onFocus={this.doFocusEvent.bind(this,true)}
							onBlur={this.doFocusEvent.bind(this,false)}
							style={style} />);
			}
			const isRequired = viewAttr === 3 && trim(value).length === 0;
			domArr.push(<span id={`${fieldName}span`} className="wf-input-required">
				{isRequired ? <img src="/images/BacoError_wev9.png" align="absmiddle" /> : ""}
			</span>);
			return(
				<div className="wea-wf-input">
					{domArr}
				</div>
			)
		}
	}
	setInputText(e) {
		const {detailtype,length,fieldlabel} = this.props;
		let value  = e.target.value;
		if(detailtype === 1) {
			let valLen = InputUtil.realLength(value);
			if(length && valLen > length) {
				message.warning(`${fieldlabel}文本长度不能超过${length}(1个中文字符等于3个长度)`);
				value  =  InputUtil.checkLength(value,valLen,length);
			}
		}
		this.setState({value:value});
	}
	doFocusEvent(bool,e){
		if(this.props.viewAttr === 1)
			return;
		if(bool){	//获取焦点
			this.setState({isonfocus:bool, location:this.getLocation()})
		}else{		//失去焦点
			let value = this.checkLen(e.target.value);	//验证长度
			let realValue = this.transRealValue(value);
			let formatValue = this.transFormatValue(value, this.props.format);
			this.setState({value:realValue, formatvalue:formatValue, isonfocus:bool});
		}
	}
	transRealValue(value){
		const {detailtype, qfws} = this.props;
		let realValue = value;
		if(detailtype !== 1){
			let isqfw = detailtype === 5;
			realValue = InputUtil.convertFloatValue(value,qfws,isqfw);
		}
		this.props.onChange && this.props.onChange(realValue);	//失去焦点触发修改Redux
		return realValue;
	}
	transFormatValue(value, format){
		let {detailtype,qfws} = this.props;
		if(detailtype !== 1){
			value = trim(value).length > 0 ? value.replace(/\,/g,'') : '';
		}
		let formatvalue = value;
		const numberType = parseInt(format.numberType)||0;
		//失去焦点
		if(numberType > 0){
			if(numberType === 100 ){ //财务预览
			}else if(numberType === 101 ){ //财务金额大写
				formatvalue = InputUtil.convertAmountChinese(value);
			}else{
				formatvalue = InputUtil.convertFormatValue(value, format);
			}
		}else{
			if(detailtype !==1){
				let isqfw = false;
				if(detailtype === 4 || detailtype === 5){
					isqfw = true;
				}
				formatvalue = InputUtil.convertFloatValue(value, qfws, isqfw);
			}
		}
		return formatvalue;
	}
	checkLen(val){
		let {detailtype,length,qfws,fieldlabel} = this.props;
		if(detailtype === 1) {
			let valLen = InputUtil.realLength(val);
			if(length && valLen > length) {
				message.warning(`${fieldlabel}文本长度不能超过${length},(1个中文字符等于3个长度)`);
				val  =  InputUtil.checkLength(val,valLen,length);
			}
			return val;
		}
		if(trim(val).length === 0 ) return "";
		if(trim(val).length === 1 && val.charCodeAt(0) === 45) return val;
		if(!InputUtil.judgeIsNumber(val))
			return "";
		if(val.charCodeAt(0) === 45) length = length + 1;
		const arr = val.toString().split(".");
		if(trim(arr[0]).length > length - qfws) {
			message.warning(`整数位数长度不能超过${length-qfws}位，请重新输入！`,5);
			return "";
		}
		return val;
	}

	//整数
	doKeyPressCheckInteger(e) {
		const keyCode = e.nativeEvent.keyCode;
		const {value} = this.state;
		let {length} = this.props;
		const isNumber = (keyCode >= 48 && keyCode <= 57) || keyCode === 45;
		const selectLen = trim(this.getSelectionText(e).toString()).length;
		if(trim(value).length > 0 && value.charCodeAt(0) === 45) length = length +1;
		if(keyCode === 45 && trim(value).length === length){
			const carePos =  this.getCursortPosition();
			if(carePos === 0){
				length = length +1;
			}
		}
		if(!isNumber || (trim(value).length - selectLen) >= length ) {
			e.preventDefault()
		}
	}
	
	doKeyDown(e){
		const {enableInput} = this.props;
		if(enableInput === false) {
			this.props.onDisablePrompt();
			e.preventDefault();
			return;
		}
		const keyCode = e.nativeEvent.keyCode;
		if(keyCode === 13){
			e.preventDefault();		//阻止enter键导致表单提交
		}
		e.stopPropagation();	//阻止冒泡
	}

	//检测小数输入
	doKeyPressCheckFloat(e) {
		const {length,qfws,detailtype} = this.props;
		const keyCode = e.nativeEvent.keyCode;
		let tmpvalue = this.state.value;
		if(detailtype !==1){
			tmpvalue = trim(tmpvalue).length > 0 ? tmpvalue.replace(/\,/g,'') : '';
		}
		const selectVal = this.getSelectionText(e).toString();
		if(selectVal.length > 0 && trim(tmpvalue).length > 0){
			const curPosition  = this.getCursortPosition();
			tmpvalue = tmpvalue.substr(0,curPosition) + tmpvalue.substr(curPosition + selectVal.length);
		}
		// 排除backspance 和del
		if(keyCode == 8) {
			return;
		}
		if(trim(tmpvalue).length === 0 && keyCode == 46){
			e.preventDefault();
		}
		let dotCount = 0;
		let integerCount = 0;
		let afterDotCount = 0;
		let hasDot = false;
		const len = trim(tmpvalue).length;
		for(i = 0; i < len; i++) {
			if(tmpvalue.charAt(i) == ".") {
				dotCount++;
				hasDot = true;
			} else {
				if(hasDot) {
					afterDotCount++;
				} else {
					integerCount++;
				}
			}
		}
		//只能输入一个"."
		if(keyCode == 46 && (hasDot || qfws === 0)){
			e.preventDefault();
		}
		//console.log("dotCount",dotCount,"integerCount",integerCount,"hasDot",hasDot,"afterDotCount",afterDotCount,"keyCode",keyCode);
		const isNumber = keyCode >= 48 && keyCode <= 57;
		const checkInput  = (isNumber || keyCode == 46 || keyCode == 45) || (keyCode == 46 && dotCount == 1);
		if(!checkInput) {
			e.preventDefault();
		}
		const checkInteger = integerCount >= length - qfws && hasDot == false && isNumber;
		if(checkInteger) {
			e.preventDefault();
		}
		const checkLen = afterDotCount >= qfws && (integerCount >= length - qfws);
		if(checkLen) {
			e.preventDefault();
		}
		if(hasDot){
			const carePos =  this.getCursortPosition();
			const dotIndex = trim(tmpvalue).indexOf('.');
			//console.log("carePos",carePos,"dotIndex",dotIndex);
			if(carePos <= dotIndex){
				if(integerCount >= length - qfws){
					e.preventDefault();
				}
			}else{
				if(afterDotCount >= qfws){
					e.preventDefault();
				}
			}
		}
	}
	getSelectionText(e){
		if (document.selection) {	//IE
			return document.selection.createRange().text;
		}else if (window.getSelection().toString()) {		//Chrome
			return window.getSelection().toString();
		}else if (e.selectionStart != undefined && e.selectionEnd != undefined) {	//其它情况
			var start = e.selectionStart;
			var end = e.selectionEnd;
			return e.value.substring(start, end);
		}
		return "";
	}
	getCursortPosition() {
		const input = this.refs.inputEle;
	    var CaretPos = 0;
	    if (input.selection) {
	        input.focus();
	        var Sel = input.selection.createRange();
	        if(Sel.text.length < 1) {
	            Sel.moveStart('character', -input.value.length);
	            CaretPos = Sel.text.length;
	        }
	    } else if (input.selectionStart || input.selectionStart == '0') { //ff
	        CaretPos = input.selectionStart;
	    }
	    return CaretPos;
	}
	getLocation(){
		try{ 	//计算鼠标焦点位置
			const elm = this.refs.inputEle;
			if(elm.createTextRange) { // IE              
				const range = document.selection.createRange();                
				range.setEndPoint('StartToStart', elm.createTextRange());                
				return range.text.length; 
			} else if(typeof elm.selectionStart === 'number') {
				return elm.selectionStart; 
			}
		}catch(e){
			return -1;
		}
	}
	setLocation(){
		const elm = this.refs.inputEle;
		let location = this.state.location;
		if(location < 0 || location > elm.value.length)	//定位到最后
        	location = elm.value.length;
		if(elm.createTextRange) {	//IE
			let textRange = elm.createTextRange();
			textRange.moveStart('character', location);
			textRange.collapse();
			textRange.select();
		} else if(elm.setSelectionRange) {
			elm.setSelectionRange(location, location); 
			elm.focus(); 
		}
	}
	
}

export default Main;